﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Threading.Tasks;
using Ls.Utils;
using Ls.Web.Api.Models;
using Ls.Web.Framework;
using Ls.Web.Framework.Jwt;
using Ls.Web.Framework.Permissions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace Ls.Web.Api.Controllers
{

    public class TokenController : BaseController
    {
        private readonly JwtSecurityTokenOptions _jwtOptions;

        UserService userService = new UserService();
        SysLogService logService = new SysLogService();

        public TokenController(IOptions<JwtSecurityTokenOptions> jwtOptions)
        {
            _jwtOptions = jwtOptions.Value;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns> 
        /// <remarks>
        /// 返回值:
        /// 
        ///      {
        ///         "resultCode": "状态",
        ///         "data": {
        ///             "token": "token",
        ///             "expires": 过期时间
        ///         }
        ///      } 
        /// </remarks>
        [HttpPost]
        [Route("/token/login")]
        public IActionResult Login(string username, string password)
        {
            try
            {
                //string username = CommonHelper.ToString( Request.Form["username"]);
                //string password = CommonHelper.ToString(Request.Form["password"]);

                dynamic user = userService.Single("user_id,nickname,realname,username,userpwd,salt,is_sup,user_type,org_id", new { username = username  });

                if (user != null && user.userpwd == CryptoHelper.MD5(password + user.salt))
                {
                    if (CommonHelper.ToInt(user.user_type) != 2 || CommonHelper.ToInt(user.user_status) != 0)
                    {
                        return GetErrorResult("您没有APP登录的权限");
                    }

                    long user_id = CommonHelper.ToInt64(user.user_id);
                    // 更新登录时间
                    userService.Update(new { last_login_time = DateTime.Now, last_login_ip = HttpContext.GetUserIp() }, new { user_id = user_id });
                    // 添加登录日志
                    logService.Insert(new
                    {
                        user_id = user_id,
                        operation = "App登录",
                        method = "LoginApp",
                        opt_params = string.Format("用户【{0}】登录", user.realname),
                        create_id = user_id,
                        ip = HttpContext.GetUserIp(),
                        create_time = DateTime.Now
                    });
                    RemoveUserInfoCache(user_id);
                }
                else
                {
                    return GetErrorResult("帐号或密码错误！");
                }
                long org_id = CommonHelper.ToInt64(user.org_id);

                var claims = new[]
                {
                    new Claim("userid", CommonHelper.ToInt64(user.user_id).ToString()),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    //new Claim("realname", CommonHelper.ToString(user.realname)),
                    //new Claim("org_id", org_id.ToString()), 
                };

                var jwtSecurityToken = new JwtSecurityToken(
                    issuer: _jwtOptions.Issuer,
                    audience: _jwtOptions.Audience,
                    claims: claims,
                    expires: DateTime.UtcNow.AddMinutes(_jwtOptions.Expires),
                    signingCredentials: _jwtOptions.SigningCredentials
                );

                return GetSuccessResult(new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken),
                    expires = _jwtOptions.Expires
                });

            }
            catch (Exception exception)
            {
                return GetErrorResult(exception.Message);
            }
        }
        /// <summary>
        /// 获取UserInfo
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// 返回值:
        /// 
        ///      {
        ///          "resultCode": "200", //状态
        ///          "data": {
        ///              "userId": 3,     // 用户Id
        ///              "realName": "门店测试账号", // 用户姓名
        ///              "carrierId": 2,           // 运营商id
        ///              "carrierCode": "100",     // 运营商编码 
        ///              "carrierName": "运营商1（trx测试用）",  // 运营商名称
        ///              "storeId": 16,            // 门店Id
        ///              "storeCode": "000203",    // 门店编码
        ///              "storeName": "测师门店",   // 门店名称
        ///              "orgId": 16,              // 所在Orgid
        ///              "whId": 16,               // 对应仓库id
        ///              "whName": "测试4"          // 对应仓库名称
        ///          }
        ///      }
        /// </remarks>
        [HttpGet]
        [Route("/token/info")]
        [Permission("App.Token.Info")]
        public IActionResult GetUserInfo()
        {
            string userId = this.UserId.ToString();

            if (userId.IsNullOrEmpty() || userId == "0")
            {
                return GetErrorResult("未登录");
            }
            var userInfo = this.UserInfo;
            if (userInfo == null)
            {
                return GetErrorResult("未登录");
            }
            else
            {
                return GetSuccessResult(userInfo);

            }

        }
    }
}